package com.xzcs.controller.login;

import com.xzcs.controller.BaseController;
import com.xzcs.util.web.ResponseUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台登录
 * @author chang
 * @createDate 2015-6-23
 */
@Controller
public class LoginController extends BaseController {

	@RequestMapping(value = "/")
	public String welcome(HttpServletRequest request) {
		return login(request);
	}

	@RequestMapping(value = "login.do")
	public String login(HttpServletRequest request) {
		Subject user = SecurityUtils.getSubject();
		if (user.isAuthenticated()) {//如果用户已登录则跳转到首页
			return "redirect:/index.do";
		}
		return "html/login";
	}
	
	@RequestMapping(value = "doLogin.do")
	public String doLogin(HttpServletRequest request) {
		String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");
		if(LockedAccountException.class.getName().equals(exceptionClassName)) {
			//logger.debug("用户被锁定");
			request.setAttribute("loginRes", -2);
        } else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
            //logger.debug("登录错误次数过多");
			request.setAttribute("loginRes", -1);
        } else if(UnknownAccountException.class.getName().equals(exceptionClassName)
        		||AuthenticationException.class.getName().equals(exceptionClassName)
        		||IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
        	//logger.debug("用户或密码不正确");
			request.setAttribute("loginRes", 0);
        } else if(null != exceptionClassName) {
        	//logger.debug("其他错误："+exceptionClassName);
			request.setAttribute("loginRes", 0);
        }
		return "html/login";
	}
	
	@RequestMapping(value = "loginOut.do")
	public void loginOut(HttpServletRequest request, HttpServletResponse response) {
		// 使用权限管理工具进行用户的退出，注销登录
		Subject user = SecurityUtils.getSubject();
		if (user.isAuthenticated()) {//登录
			user.logout();
		}
		ResponseUtils.writeText(1, response);
	}

	@RequestMapping(value = "index.do")
	public String index(HttpServletRequest request) {
		return "html/index";
	}

	@RequestMapping(value = "module.do")
	public String module(HttpServletRequest request) {
		return "html/module";
	}

	@RequestMapping(value = "home.do")
	public String home() {
		return "html/main/home";
	}
}
